package com.practice.mybatis.v2.result;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;

import org.apache.ibatis.reflection.factory.DefaultObjectFactory;

import com.practice.mybatis.v2.config.Configuration;

public class ResultHandler {
	
	private Configuration configuration;

	public ResultHandler(Configuration configuration) {
		this.configuration = configuration;
	}

	public <E> E handler(ResultSet rs, Class<E> type) throws Exception {
		Object resultObj = new DefaultObjectFactory().create(type);
		if (rs.next()) {
			int i = 0;
			for (Field field : resultObj.getClass().getDeclaredFields()) {
				setValue(resultObj, field, rs, i);
			}
		}
		return (E) resultObj;
	}

	private void setValue(Object resultObj, Field field, ResultSet rs, int i) throws Exception {
		Method method = resultObj.getClass().getMethod("set" + upperCapital(field.getName()), field.getType());
		method.invoke(resultObj, getResult(field,rs));
	}
	
	private Object getResult(Field field, ResultSet rs) throws Exception {
		Class<?> type = field.getType();
        if(Integer.class == type){
            return rs.getInt(field.getName());
        }
        if(String.class == type){
            return rs.getString(field.getName());
        }
        return rs.getString(field.getName());
	}

	private String upperCapital(String name) {
        String first = name.substring(0, 1);
        String tail = name.substring(1);
        return first.toUpperCase() + tail;
    }

}
